package com.sise.netty.基于jboss的序列化方案;


import com.sise.netty.Gzip流应用.GzipUtil;
import com.sise.netty.基于jboss的序列化方案.dto.RequestDto;
import com.sise.netty.基于jboss的序列化方案.dto.ResponseDto;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Random;

/**
 * @author idea
 * @data 2019/4/14
 */
@ChannelHandler.Sharable
public class ServerHandle extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("[server] 接受信息处理器");
        String result = msg.toString();
        System.out.println("[server] from client " + result);
        if (msg instanceof RequestDto) {
            RequestDto requestDto = (RequestDto) msg;
            //解压处理
            byte[] clientMsg = GzipUtil.unzip(requestDto.getRequestMsg());
            //客户端发送的数据信息
            System.out.println(new String(clientMsg));
        }
        byte[] serverResponse = GzipUtil.zip("this is server response".getBytes());
        ResponseDto responseDto = new ResponseDto(new Random().nextInt(10000), serverResponse);

        //写入缓冲区并行刷新发送
        ctx.writeAndFlush(responseDto);
    }


    @Override
    public void channelReadComplete(final ChannelHandlerContext ctx) {
        ctx.flush();
    }


    @Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            ctx.close();
        }
    }
}
